<template>
  <div class="app-container">
    <!--搜索条件-->
    <div class="filter-container">
      <el-row>
        <el-col :span="11">
          <el-row>
            <el-col :span="7">
              <el-input
                v-model="listQuery.keyword"
                placeholder="分销商/供货商"
                style="width: 200px;"
                class="filter-item"
                clearable
              />
            </el-col>
            <el-col :span="13">
              <el-date-picker
                v-model="listQuery.time"
                :picker-options="pickerOptions"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                align="right"
              />
            </el-col>
            <el-col :span="1">
              <el-button
                class="filter-item"
                type="primary"
                icon="el-icon-search"
                @click="searchFrom"
              >{{ $t('table.search') }}</el-button>
            </el-col>
          </el-row>
        </el-col>
        <el-col :span="2">
          <!--弹出添加框start-->
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-edit"
            @click="dialogFormVisible = true"
          >{{ $t('table.add') }}</el-button>
          <el-dialog
            :visible.sync="dialogFormVisible"
            :before-close="dialogCancle"
            width="60%"
            title="添加发货记录"
          >
            <el-form
              ref="dynamicValidateForm"
              :rules="rules"
              :inline="true"
              :model="dynamicValidateForm"
              label-width="80px"
              class="demo-form-inline"
            >
              <el-form-item label="分销商" prop="disId">
                <el-select
                  v-model="dynamicValidateForm.disId"
                  placeholder="请选择分销商"
                  style="width: 250px;"
                >
                  <el-option
                    v-for="dis in disList"
                    :label="dis.disName"
                    :value="dis.disId"
                    :key="dis.disId"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="供货商" prop="partnerId">
                <el-select
                  v-model="dynamicValidateForm.partnerId"
                  placeholder="请选择供货商"
                  style="width: 250px;"
                >
                  <el-option
                    v-for="partnerlist in partnerList"
                    :label="partnerlist.text"
                    :value="partnerlist.value"
                    :key="partnerlist.value"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="总金额" prop="productTotalAmount">
                <el-input
                  v-model="dynamicValidateForm.productTotalAmount"
                  placeholder="0.00"
                  style="width: 250px;"
                  clearable
                />
              </el-form-item>
              <el-form-item label="发货时间" prop="createDatetime">
                <el-date-picker
                  v-model="dynamicValidateForm.createDatetime"
                  type="date"
                  placeholder="选择日期"
                  style="width:250px;"
                />
              </el-form-item>
              <el-form-item label="发货单号" prop="shipmentNo">
                <el-input v-model="dynamicValidateForm.shipmentNo" style="width: 250px;" clearable/>
              </el-form-item>
              <el-form-item label="添加明细">
                <el-button style="margin-left:80px;" @click="addDetail">+</el-button>
              </el-form-item>

              <el-form-item
                v-for="(detail, index) in dynamicValidateForm.details"
                :key="index"
                :label="'物资明细'"
              >
                <el-form-item label="名称">
                  <el-input v-model="detail.productName" clearable style="width: 200px;"/>
                </el-form-item>
                <el-form-item label="产品规格">
                  <el-input v-model="detail.productSpecifications" clearable style="width: 200px;"/>
                </el-form-item>
                <el-form-item label="数量">
                  <el-input v-model="detail.productCnt" type="number" style="width: 200px;"/>
                </el-form-item>
                <el-form-item label="单价">
                  <el-input v-model="detail.productPrice" clearable style="width: 200px;"/>
                </el-form-item>
                <el-form-item label="单位">
                  <el-input v-model="detail.productUnit" clearable style="width: 200px;"/>
                </el-form-item>
                <el-form-item label="品类">
                  <el-input v-model="detail.productCategory" clearable style="width: 200px;"/>
                </el-form-item>
                <el-form-item label="品牌">
                  <el-input v-model="detail.productBrand" clearable style="width: 200px;"/>
                </el-form-item>

                <el-button @click.prevent="resetForm(detail)">重置</el-button>
                <el-button @click.prevent="removeDetail(detail)">删除</el-button>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogCancle">取 消</el-button>
              <el-button type="primary" @click="submitForm('dynamicValidateForm')">提交</el-button>
              <!-- <el-button type="primary" @click="">确 定</el-button> -->
            </div>
          </el-dialog>
          <!--弹出添加框end-->
        </el-col>
      </el-row>
    </div>
    <!--表格-->
    <el-table
      v-loading="listLoading"
      :data="talelist"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column fixed prop="disName" label="分销商" width="150"/>
      <el-table-column prop="partnerName" label="供货商" width="120"/>
      <el-table-column prop="shipmentNo" label="发货单号" width="150"/>
      <el-table-column prop="productTotalAmount" label="发货单总金额" width="120"/>
      <el-table-column prop="createDatetime" label="发货时间" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.createDatetime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column prop label="操作" width="120"/>
    </el-table>

    <!--分页-->
    <div class="pagination-container">
      <el-pagination
        v-show="total>0"
        :current-page="listQuery.page"
        :page-sizes="[2,20,30, 50]"
        :page-size="listQuery.pageSize"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script>
import { fetchList, addShipmentAndDetails } from '@/api/shipment'
import { distributorList } from '@/api/payment'
import { parseTime } from '@/utils'

export default {
  data() {
    var validateNumber = (rule, value, callback) => {
      if (!Number(value)) {
        callback(new Error('请输入数字值'))
      } else {
        const regu = /^[0-9]+(\.[0-9]{1,2})?$/
        const rsCheck = regu.test(value)
        if (!rsCheck) {
          callback(new Error('请输入正确的金额类型'))
        }
        callback()
      }
    }

    return {
      disList: null,
      partnerList: [
        {
          value: '73250',
          text: '美博'
        },
        {
          value: '73251',
          text: '长沙供应商'
        }
      ],
      dialogFormVisible: false,
      talelist: null,
      total: 1,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 2,
        keyword: null,
        starTime: null,
        endTime: null,
        time: null,
        pageNumber: null
      },
      shipmentNo: null,
      rules: {
        shipmentNo: [
          { required: true, message: '请输入发货单号', trigger: 'blur' }
        ],
        disId: [{ required: true, message: '请选择分销商', trigger: 'blur' }],
        partnerId: [
          { required: true, message: '请选择合作商', trigger: 'blur' }
        ],
        productTotalAmount: [{ validator: validateNumber, trigger: 'blur' }],
        createDatetime: [
          { required: true, message: '请选择发货时间', trigger: 'blur' }
        ]
      },
      dynamicValidateForm: {
        disId: null,
        disName: null,
        partnerId: null,
        partnerName: null,
        shipmentNo: null,
        productTotalAmount: null,
        createDatetime: null,
        details: [
          {
            productName: '',
            productSpecifications: '',
            productCnt: '',
            productAmount: '',
            productCategory: '',
            productBrand: '',
            productPrice: '',
            productUnit: ''
          }
        ]
      },
      form: {},
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      time: ''
    }
  },
  created() {
    this.getList()
    this.getDistributorList()
  },
  methods: {
    getList() {
      this.listLoading = true
      var vmthis = this
      this.listQuery.pageNumber =
        (this.listQuery.page - 1) * this.listQuery.pageSize
      fetchList(this.listQuery)
        .then(response => {
          if (response.data.status === 'success') {
            vmthis.total = response.data.data.total
            vmthis.talelist = response.data.data.list
            vmthis.listLoading = false
          }
        })
        .catch(error => {
          console.log(error)
          vmthis.listLoading = false
        })
    },
    // 查询分销商
    getDistributorList() {
      distributorList().then(response => {
        this.disList = response.data.data
      })
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    searchFrom() {
      if (this.listQuery.time !== null && this.listQuery.time !== '') {
        this.listQuery.starTime = parseTime(
          this.listQuery.time[0],
          '{y}-{m}-{d} {h}:{i}'
        )
        this.listQuery.endTime = parseTime(
          this.listQuery.time[1],
          '{y}-{m}-{d} {h}:{i}'
        )
      } else {
        this.listQuery.starTime = null
        this.listQuery.endTime = null
      }
      this.listQuery.pageNumber = 0
      this.getList()
    },
    addDetail() {
      // 添加表单
      this.dynamicValidateForm.details.push({
        productName: '',
        productSpecifications: '',
        productCnt: '',
        productAmount: '',
        productCategory: '',
        productBrand: '',
        productPrice: '',
        productUnit: ''
      })
    },
    removeDetail(item) {
      // 删除表单
      var index = this.dynamicValidateForm.details.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.details.splice(index, 1)
      }
    },
    submitForm(formName) {
      // 提交集合表单
      this.$refs[formName].validate(valid => {
        if (valid) {
          var time = parseTime(
            this.dynamicValidateForm.createDatetime,
            '{y}-{m}-{d}'
          )
          this.dynamicValidateForm.createDatetime = time

          var disName
          for (var i = 0; i < this.disList.length; i++) {
            if (this.disList[i].disId === this.dynamicValidateForm.disId) {
              disName = this.disList[i].disName
            }
          }
          this.dynamicValidateForm.disName = disName

          var partnerName
          for (var j = 0; j < this.partnerList.length; j++) {
            if (
              this.partnerList[j].value === this.dynamicValidateForm.partnerId
            ) {
              partnerName = this.partnerList[j].text
            }
          }
          this.dynamicValidateForm.partnerName = partnerName
          console.log(
            '===========' +
              JSON.stringify(this.$refs['dynamicValidateForm'].model)
          )
          this.shipmentNo = JSON.stringify(
            this.$refs['dynamicValidateForm'].model
          )
          var param = {
            shipmentNo: this.shipmentNo
          }
          var vmthis = this
          addShipmentAndDetails(param)
            .then(response => {
              if (response.data.status === 'success') {
                this.$message({
                  message: '添加成功',
                  type: 'success'
                })
                setTimeout(() => {
                  this.dialogFormVisible = false
                }, 1.5 * 1000)
                this.getList()
              } else {
                this.$message({
                  message: '添加失败：' + response.data.messge,
                  type: 'error'
                })
              }
            })
            .catch(error => {
              console.log(error)
              vmthis.listLoading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(item) {
      // 清空表单
      var index = this.dynamicValidateForm.details.indexOf(item)

      if (index !== -1) {
        this.dynamicValidateForm.details.splice(index, 1, {
          productName: '',
          productSpecifications: '',
          productCnt: '',
          productAmount: '',
          productCategory: '',
          productBrand: '',
          productPrice: '',
          productUnit: ''
        })
      }
    },
    dialogCancle() {
      this.dialogFormVisible = false
      this.dynamicValidateForm = {
        disId: null,
        partnerName: null,
        shipmentNo: null,
        productTotalAmount: null,
        createDatetime: null,
        details: [
          {
            productName: '',
            productSpecifications: '',
            productCnt: '',
            productAmount: '',
            productCategory: '',
            productBrand: '',
            productPrice: '',
            productUnit: ''
          }
        ]
      }
    }
  }
}
</script>
